package longrise.phone.com.bjjt_henan.main;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.ui.AbstractSpinerAdapter;
import com.longrise.bjjt.util.AllCapTransformationMethod;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_henan.Adapter.PictureAdapter;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.BDLocationManager;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;
import longrise.phone.com.bjjt_henan.compensate.HeNanSurfaceViewCameraActivity;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

/**
 * 违章举报界面
 */

public class PeccancyReportView extends LFView implements View.OnClickListener, AdapterView.OnItemClickListener,
        AbstractSpinerAdapter.IOnItemSelectListener, BDLocationListener, MainActivity.OnActivityReturnBitmap {

    private Context mContext;

    private View mView;

    private TextView aTypeTV;

    private TextView addressTV;

    private LinearLayout roadLLayout;

    private EditText roadTV;

    private TextView picInfoTV;

    private GridView picGView;

    private LinearLayout cTypeLLayout;

    private TextView cTypeTV;

    private LinearLayout carnumLLayout;

    private TextView carnumTV;

    private EditText carnumET;

    private CheckBox infoCBox;

    private TextView infoTV;

    private Button comitBtn;

    private int type;//违章类型

    private String typeStr;

    private BDLocationManager manager;

    private String carType;//车辆类型（0表示小型；1表示大型）

    public static int DSIZE = 4;//默认总数目

    private List<EntityBean> picLists;//显示的图片集合

    private PictureAdapter picAdapter;

    private EntityBean curBean;//当前点击的选项

    private View curView;//准备刷新的view

    private int curPos;

    private Dialog processDialog;

    private BaseApplication mApplication;

    private PromptDialog dialog;

    private static final int SUCCESS = 0;

    private static final int FAIL = 1;

    private List<String> carnoStrs;

    private String appcaseno;

    private String areaid;

    private String latitude;

    private String longitude;

    public PeccancyReportView(Context context, int type, String typeStr) {
        super(context);
        this.mContext = context;
        this.type = type;
        this.typeStr = typeStr;
        this.mApplication = ((MainActivity) context).getAppData();
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter form = new FormParameter();
        form.setShowtitle(false);
        return form;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void init() {
        mView = View.inflate(mContext, R.layout.view_peccancyreport, null);
        //标题栏
        TextView titleTV = (TextView) mView.findViewById(R.id.tv_title);
        mView.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });
        titleTV.setText(typeStr);
        aTypeTV = (TextView) mView.findViewById(R.id.report_tv_atype);
        addressTV = (TextView) mView.findViewById(R.id.report_tv_address);
        roadLLayout = (LinearLayout) mView.findViewById(R.id.report_ll_road);
        roadTV = (EditText) mView.findViewById(R.id.report_et_road);
        picInfoTV = (TextView) mView.findViewById(R.id.report_tv_picinfo);
        picGView = (GridView) mView.findViewById(R.id.report_gv);
        cTypeLLayout = (LinearLayout) mView.findViewById(R.id.report_ll_car);
        cTypeTV = (TextView) mView.findViewById(R.id.report_tv_car);
        carnumLLayout = (LinearLayout) mView.findViewById(R.id.report_ll_carnum);
        carnumTV = (TextView) mView.findViewById(R.id.report_tv_carnum);
        carnumET = (EditText) mView.findViewById(R.id.report_et_carnum);
        infoCBox = (CheckBox) mView.findViewById(R.id.report_cbox);
        infoTV = (TextView) mView.findViewById(R.id.report_tv_info);
        comitBtn = (Button) mView.findViewById(R.id.report_btn_commit);

        initValue();
    }

    private void initValue() {
        aTypeTV.setText(typeStr);
        if (manager == null) {
            manager = new BDLocationManager(mContext, true);
            manager.setLocationListener(this);
        }
        if (picLists == null) {
            picLists = new ArrayList<EntityBean>();
        } else {
            picLists.clear();
        }
        if (type == 4) {//违章停车
            roadLLayout.setVisibility(View.VISIBLE);
            picInfoTV.setText("(必填)");
            picLists.add(getBean("31", CommontUtils.getImgTypeStr("31")));
            picLists.add(getBean("32", CommontUtils.getImgTypeStr("32")));
            picLists.add(getBean("33", CommontUtils.getImgTypeStr("33")));
            picLists.add(getBean("34", CommontUtils.getImgTypeStr("34")));
        } else {//其他类型
            roadLLayout.setVisibility(View.GONE);
            picLists.add(getBean("35", CommontUtils.getImgTypeStr("35")));
            picLists.add(getBean("-1", CommontUtils.getImgTypeStr("-1")));
        }
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        float screenWidth = dm.widthPixels;
        picAdapter = new PictureAdapter(mContext, screenWidth);
        picGView.setAdapter(picAdapter);
        picAdapter.setLists(picLists);
        picAdapter.notifyDataSetChanged();

        carnumET.setTransformationMethod(new AllCapTransformationMethod());
        String info = mContext.getResources().getString(R.string.report_info);
        int color = mContext.getResources().getColor(R.color.themecolor);
        infoTV.setText(CommontUtils.changeStrColor(info, "《随手拍举报须知》", color));

        carnoStrs = CommontUtils.getCarnoShorts();
        setEvent(true);
    }

    //获取默认显示图片
    private EntityBean getBean(String type, String desc) {
        EntityBean bean = new EntityBean();
        bean.set("type", type);
        bean.set("desc", desc);

        return bean;
    }

    private void setEvent(boolean flag) {
        if (null != cTypeLLayout) {
            cTypeLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != carnumLLayout) {
            carnumLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != infoTV) {
            infoTV.setOnClickListener(flag ? this : null);
        }
        if (null != comitBtn) {
            comitBtn.setOnClickListener(flag ? this : null);
        }
        if (null != picGView) {
            picGView.setOnItemClickListener(flag ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.report_ll_car://车型
                UiUtil.showSelectPopWindow(mContext, getCarType(), this, cTypeLLayout, true);
                break;
            case R.id.report_ll_carnum://车牌
                UiUtil.showSelectPopWindow(mContext, carnoStrs, this, carnumLLayout, true);
                break;
            case R.id.report_tv_info://举报须知
                showInfoDialog();
                break;
            case R.id.report_btn_commit://提交
                commit();
                break;
            default:
                break;
        }
    }

    //提交信息
    private void commit() {
        if (!checkTakePhoto()) {
            UiUtil.showToast(getContext(), "请完善违法照片！");
            return;
        }
        String carnoSuffix = carnumET.getText().toString().trim().toUpperCase();
        String carno = null;
        if (!TextUtils.isEmpty(carnoSuffix)) {
            carno = carnumTV.getText().toString() + carnoSuffix;
            if (!StringUtils.isCar(carno)) {
                UiUtil.showToast(mContext, "请输入合法的车牌号码！");
                return;
            }
        }
        if (!infoCBox.isChecked()) {
            UiUtil.showToast(mContext, "请同意随手拍举报须知！");
            return;
        }
        EntityBean baseBean = mApplication.getLoginInfo().getBean("userinfo");
        String phone = baseBean.getString("mobilephone");
        String uname = baseBean.getString("name");
        String place = addressTV.getText().toString().trim();
        String street = roadTV.getText().toString().trim();
        String uid = mApplication.getKckpName();
        String token = mApplication.getToken();
        DialogUtils.showDialog(mContext);
        ApiImpI.getInstance(mContext.getApplicationContext()).submitInfo(appcaseno, carno, phone, longitude, latitude,
                place, street, carType, areaid, Integer.toString(type), uname, uid, token, new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(getContext(), error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        if (mView == null) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals("1", restate)) {
                            showReportDialog();
                        } else {
                            String redes = bean.getString("redes");
                            if (!TextUtils.isEmpty(redes)) {
                                UiUtil.showToast(mContext, redes);
                            }
                        }
                    }
                }
        );
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (TextUtils.isEmpty(areaid) || TextUtils.isEmpty(appcaseno)) {
            UiUtil.showToast(mContext, "正在获取定位中，请稍后。。。");
            return;
        }
        curBean = picLists.get(position);
        curView = view;
        curPos = position;
        String type = curBean.getString("type");
        if (TextUtils.equals(type, "-1")) {//点击的+号图标
            if (picLists.size() > DSIZE) {
                UiUtil.showToast(mContext, "拍照数目已达上限！");
                return;
            }
        }
        getCamera(curBean.getString("desc"), null, 0);
    }

    //启动相机
    public void getCamera(String title, String titleBottom, int resourceId) {
        if (!PermissionHelper.checkCameraPermissions(mContext)) {
            return;
        }
        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }

        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);

        if (mContext instanceof MainActivity) {
            ((MainActivity) mContext).startActivityForResult(intent, 110);
        }
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode, Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            if (requestCode == 66) {
                manager.bdLocation();
            } else if (requestCode == 110) {
                Bundle bundle = data.getExtras();
                String path = bundle.getString("image");
                if (path == null) {
                    UiUtil.showToast(mContext, "照片拍摄失败！");
                    return;
                }
                if (null == curBean) {
                    return;
                }
                String type = curBean.getString("type");
                if (TextUtils.equals(type, "-1")) {
                    type = "30";//补拍的照片类型
                }
                //照片拍完后立即上传
                useLoadingPic(path, Integer.valueOf(type));
            }
        }
    }

    /**
     * 异步上传图片
     */
    private void useLoadingPic(final String filePath, final int imgType) {
        String address = addressTV.getText().toString().trim();
        String date = CommontUtils.getNowTime();
        String uid = mApplication.getKckpName();
        String token = mApplication.getToken();
        if (processDialog == null) {
            processDialog = UiUtils.showProcessDialogPro(getContext(), "正在上传");
        } else {
            processDialog.show();
        }
        ApiImpI.getInstance(mContext.getApplicationContext()).submitcaseimg(appcaseno, longitude, latitude,
                address, filePath, imgType, date, areaid, "4", uid, token, new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        if (null != processDialog && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (null != myHandler && !TextUtils.isEmpty(error)) {
                            myHandler.sendMessage(getMsg(FAIL, filePath, error));
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        if (null != processDialog && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (result != null) {
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                String restate = bean.getString("restate");
                                if ("1".equals(restate)) {
                                    if (null != myHandler) {
                                        myHandler.sendMessage(getMsg(SUCCESS, filePath, null));
                                    }
                                } else {
                                    if (null != myHandler) {
                                        String redes = bean.getString("redes");
                                        myHandler.sendMessage(getMsg(FAIL, filePath, redes));
                                    }
                                }
                            }
                        }
                    }
                });
    }

    private Message getMsg(int what, String path, String content) {
        Message msg = Message.obtain();
        msg.what = what;
        Bundle bundle = new Bundle();
        bundle.putString("path", path);
        bundle.putString("content", content);
        msg.setData(bundle);
        return msg;
    }

    //显示重试对话框
    private void showRetryDialog(String path, String content) {
        if (null == dialog) {
            dialog = new PromptDialog(mContext);
            dialog.setIcon(R.mipmap.warn);
            dialog.setCancel("返回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setConfirm("重试", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tagPath = (String) v.getTag();
                    dialog.dismiss();
                    processDialog.show();
                    String type = curBean.getString("type");
                    if (TextUtils.equals(type, "-1")) {
                        type = "30";//补拍的照片类型
                    }
                    useLoadingPic(tagPath, Integer.valueOf(type));
                }
            });
        }
        dialog.setConfirmTag(path);
        dialog.setInfo(content);
        dialog.show();
    }

    private void showInfoDialog() {
        final Dialog dialog = new Dialog(mContext, R.style.AlertDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_reportinfo, null);
        view.findViewById(R.id.dialog_btn_report).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        //设置大小
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.80);
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    private void showReportDialog() {
        final Dialog dialog = new Dialog(mContext, R.style.AlertDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_reportsuccess, null);
        view.findViewById(R.id.dialog_btn_report).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        //设置大小
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.80);
        dialogWindow.setAttributes(lp);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                OnDestroy();
                closeForm();
            }
        });
        dialog.show();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mView == null) {
                return;
            }
            Bundle data = msg.getData();
            String path = data.getString("path");
            switch (msg.what) {
                case SUCCESS://图片上传成功
                    String type = curBean.getString("type");
                    if (TextUtils.equals(type, "-1")) {
                        curBean = new EntityBean();//补拍照片
                        curBean.set("type", "30");
                        picLists.add(picLists.size() - 1, curBean);
                    }
                    CommontUtils.deleteFile(curBean.getString("path"));//删除之前拍的图片
                    curBean.set("path", path);
                    if (picLists.size() > DSIZE) {
                        //拍照数目已达上限则移除+号项
                        picLists.remove(picLists.size() - 1);
                    }
                    picAdapter.updateItem(curPos, curView);
                    break;
                case FAIL://上传失败则显示重试对话框
                    String content = data.getString("content");
                    showRetryDialog(path, content);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onItemClick(int pos, View view) {
        switch (view.getId()) {
            case R.id.report_ll_car:
                cTypeTV.setText(getCarType().get(pos));
                carType = String.valueOf(pos + 1);
                break;
            case R.id.report_ll_carnum://车牌
                carnumTV.setText(carnoStrs.get(pos));
                break;
            default:
                break;
        }
    }

    @Override
    public void refresh() {
        DialogUtils.showDialog(mContext);
        manager.bdLocation();
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (null == mView) {
            return;
        }
        if (null != location) {
            String cityCode = location.getCityCode();
            if (!StringUtils.isEmpty(cityCode)) {
                latitude = String.valueOf(location.getLatitude());
                longitude = String.valueOf(location.getLongitude());
                // 经纬度
                getAreaId(latitude, longitude);

                String address = location.getAddrStr();
                if (address.startsWith("中国")) {
                    address = address.substring(2);
                }
                addressTV.setText(address);
                if (type == 4) {//违章停车
                    roadTV.setText(address);
                }

                if (manager != null) {
                    manager.ondestroty();
                    manager = null;
                }
                return;
            }
        }
        DialogUtils.closeDialog();
    }

    private void getAreaId(String latitude, String longitude) {
        String userflag = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(mContext).getSspAreaid(longitude, latitude, userflag, token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(mContext, error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        if (null == mView) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            EntityBean dataBean = bean.getBean("data");
                            if (null != dataBean) {
                                areaid = dataBean.getString("areaid");
                                appcaseno = dataBean.getString("appcaseno");
                            }
                        }
                    }
                });
    }

    @Override
    public void refreshByTime() {

    }

    /**
     * 验证图片是否拍摄
     *
     * @return
     */
    private boolean checkTakePhoto() {
        int size = picLists.size();
        for (int i = 0; i < size; i++) {
            EntityBean bean = picLists.get(i);
            String type = bean.getString("type");
            if (!TextUtils.equals(type, "-1")) {
                String path = bean.getString("path");
                if (TextUtils.isEmpty(path)) {//照片未拍摄
                    return false;
                }
            }
        }
        return true;
    }

    private List<String> getCarType() {
        List<String> types = new ArrayList<>();
        types.add("小型汽车");
        types.add("大型汽车");

        return types;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        setEvent(false);

        if (null != manager) {
            manager.ondestroty();
            manager = null;
        }
        if (null != picLists) {
            picLists.clear();
            picLists = null;
        }
        if (null != carnoStrs) {
            carnoStrs.clear();
            carnoStrs = null;
        }
        if (null != picGView) {
            picGView.setAdapter(null);
            picGView = null;
        }
        if (null != dialog) {
            dialog.dismiss();
            dialog = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        myHandler = null;
        mView = null;
    }
}
